package com.itheima.reggie.common;

import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.exception.LoginException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
// 全局异常处理器
@RestControllerAdvice
public class GlobalExceptionHandler {

    // 处理新增数据时，数据异常的问题
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R saveCheckException(SQLIntegrityConstraintViolationException exception) {
        //Duplicate entry '18800010008' for key 'idx_phone'
        if (exception.getMessage().contains("Duplicate entry")) {
            //根据空格切割字符串，获取具体的信息
            String msg = exception.getMessage().split(" ")[2];
            return R.error(msg + " 已存在");
        }
        return R.error("对不起，服务器异常，请稍后重试");
    }


    // 处理删除分类管理时，分类下数据时的异常处理
    @ExceptionHandler(CustomException.class)
    public R exceptionHandler(CustomException e) {
        log.info(e.getMessage());

        return R.error(e.getMessage());
    }


    // 处理没有登陆的异常
    @ExceptionHandler(LoginException.class)
    public R loginException(LoginException e) {
        return R.error(e.getMessage());
    }

}
